package com.chujian.Threads;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.os.Handler;
import android.os.Message;
/**
 * 使用httpclient 的post方法与服务器进行交互
 * 适用于发送json串数据
 * @author cc
 *
 */
public class HttpClientPostThread extends Thread{
	private String url;
	private Handler handler;
	private String jsonString;
	public HttpClientPostThread(String url, Handler handler, String jsonString) {
		super();
		this.url = url;
		this.handler = handler;
		this.jsonString = jsonString;
	}
//	使用post方式时中文乱码
	private void dohttpClientPost(){
		HttpClient client=new DefaultHttpClient();
		HttpPost post=new HttpPost(url);
		List<NameValuePair>list =new ArrayList<NameValuePair>();
		NameValuePair nvp=new BasicNameValuePair("jsonString", jsonString);
		list.add(nvp);
		try {
//			解决中文编码乱码问题：new UrlEncodedFormEntity(list,"UTF-8")
			post.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
			HttpResponse response=client.execute(post);
			if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
//				获取返回的数据
				String content =EntityUtils.toString(response.getEntity());
//				将消息发送回主线程
				Message msg=new Message();
				msg.obj=content;
				handler.sendMessage(msg);
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		dohttpClientPost();
	}
}
